#!/bin/bash
export CONSUL_SERVER="{{ consul_server }}"
RESPONE=`curl --write-out '%{http_code}' --silent --output /dev/null $CONSUL_SERVER/v1/status/leader`
if [[ $RESPONE == 200 ]]; then 
  CONSUL_SERVER_PORT="80"
else
  CONSUL_SERVER_PORT="{{ consul_server_port }}"
fi
cat > /srv/config.hcl <<EOF
consul {
  address = "{{ consul_server }}:$CONSUL_SERVER_PORT"
  retry {
    enabled = true
    attempts = 12
    backoff = "250ms"
  }
}

template {
  source = "/srv/haproxy.cfg.ctmpl"
  destination = "/etc/haproxy/haproxy.cfg"
  command = "sudo systemctl reload haproxy"
}
EOF